package com.aqie.netty.wechat.netty;

import com.aqie.netty.wechat.netty.initializer.WebsocketServerInitalizer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;

@Component
public class WebsocketServer {
    // 内部类
    private static class SingletonWSServer{
        static final WebsocketServer instance = new WebsocketServer();
    }

    public static WebsocketServer getInstance(){
        return SingletonWSServer.instance;
    }

    private EventLoopGroup mainGroup;
    private EventLoopGroup subGroup;

    private ServerBootstrap server;
    private ChannelFuture future;

    public WebsocketServer(){
        mainGroup = new NioEventLoopGroup();
        subGroup = new  NioEventLoopGroup();
        server = new ServerBootstrap();
        server.group(mainGroup, subGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new WebsocketServerInitalizer());
    }

    public void start() {
        // 不需要同步
        this.future = server.bind(8888);
        System.err.println("netty webSocket server 启动完毕... 监听8888端口");
    }
}
